import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:core_package/core_package.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app_unionad/core/configuration.dart';
import 'package:flutter_app_unionad/event_or_delegate/reload_event.dart';
import 'package:flutter_app_unionad/model/asset_download_model.dart';
import 'package:flutter_app_unionad/model/promotion_materials_model.dart';
import 'package:flutter_app_unionad/request/facility_request.dart';
import 'package:flutter_app_unionad/ui/basice/common_position_tip.dart';
import 'package:flutter_app_unionad/ui/basice/my_button.dart';
import 'package:flutter_app_unionad/ui/basice/my_separator_widget.dart';
import 'package:flutter_app_unionad/request/promotion_request.dart';
import 'package:flutter_app_unionad/ui/basice/photo_view_page.dart';
import 'package:flutter_app_unionad/ui/my_facility/widget/select_pay_type_widget.dart';
import 'package:flutter_app_unionad/ui/promotion/widget/assets_download_save_success_widget.dart';
import 'package:flutter_app_unionad/view_model/change_device_event.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:sharesdk_plugin/sharesdk_defines.dart';
import 'package:sharesdk_plugin/sharesdk_interface.dart';
import 'package:sharesdk_plugin/sharesdk_plugin.dart';
import 'package:dio/dio.dart';
import 'package:permission_handler/permission_handler.dart';

class AssetsDownloadWidget extends StatefulWidget {
  @override
  _AssetsDownloadWidgetState createState() => _AssetsDownloadWidgetState();
}

class _AssetsDownloadWidgetState extends State<AssetsDownloadWidget> with AutomaticKeepAliveClientMixin {
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
  int page = 0;
  EasyRefreshController? _controller;
  List<PromotionMaterialsModel>? dataSource;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = EasyRefreshController();
    getData();
  }

  void getData() async {
    page = 1;
    final list = await PromotionRequest.getListByType(type: 4, pageNum: page);
    if (dataSource == null) dataSource = [];
    dataSource = list;
    if (mounted) setState(() {});
  }

  void getMoreData() async {
    page++;
    final list = await PromotionRequest.getListByType(type: 4, pageNum: page);
    if (dataSource == null) dataSource = [];
    if (list != null && list.length != 0) {
      dataSource?.addAll(list);
    }
    if (list != null && list.length < 20) {
      _controller!.finishLoadCallBack?.call();
    } else {
      _controller!.resetLoadStateCallBack?.call();
    }
    if (mounted) setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (dataSource == null) {
      return ProgressDialog.showFirstLoading();
    }
    if (dataSource!.length == 0) {
      return Center(child: EmptyWidget());
    }
    return EasyRefresh(
      header: RefreshBasics.header,
      footer: RefreshBasics.footer,
      controller: _controller,
      onRefresh: () async {
        eventBus.fire(TabViewReloadDataEvent(index: 1));
        getData();
      },
      onLoad: () async {
        getMoreData();
      },
      child: ListView.builder(
        padding: EdgeInsets.zero,
        itemCount: dataSource!.length,
        itemBuilder: (ctx, index) {
          return buildListViewItemWidget(context, dataSource![index], index);
        },
      ),
    );
  }

  Widget buildListViewItemWidget(BuildContext context, PromotionMaterialsModel model, int index) {
    GlobalKey key = GlobalKey();
    return Container(
      padding: EdgeInsets.only(left: 30.px, right: 30.px, top: 35.px),
      child: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ShowPicWidget(
                "",
                width: 45.px,
                height: 45.px,
              ),
              MySizeBox(width: 30),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    GestureDetector(
                      onLongPress: () {
                        Clipboard.setData(ClipboardData(text: model.title));
                        ShowToastWidget.showToast(msg: "复制成功");
                      },
                      child: Text(
                        model.title ?? '',
                        style: TextStyle(
                          color: MyColors.color_27_27_27,
                          fontSize: MyFont.font13,
                          fontWeight: MyFontWeight.regular,
                        ),
                      ),
                    ),
                    MySizeBox(height: 15),
                    // Text(
                    //   "博主@babyIH xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
                    //   style: TextStyle(
                    //     color: MyColors.color_27_27_27,
                    //     fontSize: MyFont.font10,
                    //     fontWeight: MyFontWeight.regular,
                    //   ),
                    // ),
                    // MySizeBox(height: 10),
                    buildGridViewWidget(model, key),
                    MySizeBox(height: 15),
                    buildShareButtonWidget(index, key)
                  ],
                ),
              ),
            ],
          ),
          MySizeBox(height: 15),
          MySeparator(height: 2),
        ],
      ),
    );
  }

  Widget buildShareButtonWidget(int index, GlobalKey key) {
    return Row(
      children: [
        Expanded(child: SizedBox()),
        MyButton(
          title: "保存",
          width: 67.px,
          height: 27.px,
          radius: 2.px,
          onTap: () {
            //下载被点击
            shareOnTap(key, index);
          },
        ),
      ],
    );
  }

  Widget buildGridViewWidget(PromotionMaterialsModel model, GlobalKey key) {
    List<String> items = [];
    if (model.content != null && model.content!.length != 0) {
      items = model.content!.split(',');
    }
    items.add('dd'); //添加最后一个为二维码
    return GridView.builder(
      padding: EdgeInsets.zero,
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      itemCount: items.length,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        childAspectRatio: 1,
        crossAxisCount: 3,
        crossAxisSpacing: 3.px,
        mainAxisSpacing: 3.px,
      ),
      itemBuilder: (ctx, index) {
        String url =
            "${Configuration.h5Share}${FacilityRequest.encodeBase64(UserCacheUil.getString(Configuration.mobile) ?? '')}";
        double width = (SizeFill.screenWidth! - 86.px) / 3 - 0.01;
        return GestureDetector(
          onTap: () {
            PhotoViewPage.showPhoto(
              context,
              dataSource: items,
              index: index,
            );
          },
          child: index == items.length - 1
              ? RepaintBoundary(
                  key: key,
                  child: Container(
                    color: Colors.white,
                    child: QrImage(
                      data: url,
                      size: width,
                      embeddedImage: AssetImage('assets/images/icon_logo_2.png'),
                      padding: EdgeInsets.zero,
                    ),
                  ),
                )
              : Container(
                  width: width,
                  child: ShowPicWidget(items[index], fit: BoxFit.fill),
                ),
        );
      },
    );
  }

  void shareOnTap(GlobalKey key, int index) async {
    var status = await Permission.storage.status;
    if (!status.isGranted) {
      status = await Permission.storage.request();
    }

    if (!status.isGranted) {
      ShowToastWidget.showToast(msg: "请开启访问相册权限");
      //这里需要开启权限
      return;
    }

    ProgressDialog.showPayFirstLoading(context, msg: '下载中...\n请稍等');
    List<String> items = [];
    if (dataSource![index].content != null && dataSource![index].content!.length != 0) {
      items = dataSource![index].content!.split(',');
    }
    for (int i = 0; i < items.length; i++) {
      var response = await Dio().get(items[i], options: Options(responseType: ResponseType.bytes));
      final result = await ImageGallerySaver.saveImage(Uint8List.fromList(response.data));
      if (result == null) {
        ProgressDialog.dismiss(context);
        ShowToastWidget.showToast(msg: '保存失败');
        return;
      }
    }
    final result = _capturePng(context, key);
    ProgressDialog.dismiss(context);
    //
    // if (result == null) {
    //   ShowToastWidget.showToast(msg: '保存失败');
    //   return;
    // }
    Clipboard.setData(ClipboardData(text: dataSource![index].title));
    AssetsDownloadSaveSuccessWidget.show(context);
  }

  Future _capturePng(BuildContext context, GlobalKey key) async {
    //检查是否有存储权限

    BuildContext? buildContext1 = key.currentContext;
    if (buildContext1 != null) {
      RenderRepaintBoundary boundary = key.currentContext!.findRenderObject() as RenderRepaintBoundary;
      var image = await boundary.toImage(pixelRatio: 6.0);
      ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData!.buffer.asUint8List();
      return savePhoto(pngBytes);
    }
  }

  Future savePhoto(Uint8List pngBytes) async {
    final result = await ImageGallerySaver.saveImage(pngBytes);
    return result;
  }
}
